package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool) // 保存所有连接的客户端

func main() {
	http.HandleFunc("/", handleWebSocket)
	log.Fatal(http.ListenAndServe(":8088", nil))
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	fmt.Println(111)
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			// 允许跨域请求
			return true
		},
	}

	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("升级为WebSocket连接失败:", err)
		return
	}
	defer conn.Close()

	// 将新连接的客户端添加到 clients 映射中
	clients[conn] = true

	for {
		// 读取前端发送的消息
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("读取WebSocket消息失败:", err)
			delete(clients, conn) // 从 clients 映射中删除断开的客户端
			break
		}

		fmt.Println("收到WebSocket消息:", string(message))

		// 向所有连接的客户端广播消息
		for client := range clients {
			err := client.WriteMessage(websocket.TextMessage, message)
			if err != nil {
				log.Println("发送WebSocket消息失败:", err)
				client.Close()
				delete(clients, client) // 从 clients 映射中删除断开的客户端
			}
		}
	}
}
